package com.qdxwx.web.controller.ajax;


import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKCookie;
import com.qdxwx.data.service.article.ArticleService;
import com.qdxwx.models.article.Article;
import com.qdxwx.models.article.ArticleQuery;
import com.qdxwx.web.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 个人中心  Controller
 * @author developer
 */
@Controller
@RequestMapping("/ajax/article")
public class AjaxArticleController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(AjaxArticleController.class);

    @Autowired
    private ArticleService articleService;


    @RequestMapping("/list.json")
    @ResponseBody
    public AjaxResult list(HttpServletRequest request){
        int orderBy = TKConvert.toInteger(request.getParameter("orderBy"));
        int page = TKConvert.toInteger(request.getParameter("page"),1);
        int limit = TKConvert.toInteger(request.getParameter("limit"),6);
        ArticleQuery query = new ArticleQuery();
        query.setOrderBy(orderBy);
        PageRequest pageRequest = new PageRequest();
        pageRequest.setCurrentPage(page);
        pageRequest.setPageSize(limit);
        List<Article> articleList = articleService.getList(query, pageRequest);
        return AjaxResult.success(articleList);
    }

    /**
     * 修改文章点击数量
     */
    @RequestMapping("/update/viewCount.json")
    @ResponseBody
    public AjaxResult articleUpdateClickNum(HttpServletRequest request) {
        int articleId = TKConvert.toInteger(request.getParameter("id"));
        articleService.updateViewCount(articleId);
        return AjaxResult.success();
    }


    /**
     * 添加点赞记录
     */
    @RequestMapping("/update/praiseCount.json")
    @ResponseBody
    public AjaxResult addPraise(HttpServletRequest request, HttpServletResponse response) {
        int articleId = TKConvert.toInteger(request.getParameter("id"));
        if (articleId < 1) {
            return AjaxResult.error("参数错误！");
        }
        if (String.valueOf(articleId).equals(TKCookie.get(request, "ArticlePraise"))) {
            return AjaxResult.error("请不要重复点赞！");
        }
        articleService.updatePraiseCount(articleId);
        TKCookie.set(response, "ArticlePraise", String.valueOf(articleId), 1);
        return AjaxResult.success();
    }
}